/**
 * require js common config
 */

/* ===================================== */
/* HTML5 Local & Session Storage         */
/* ===================================== */
(function() {
	window["getStorage"] = function(storage, key){
		return window[storage].getItem(key);
	};
	
	window["setStorage"] = function(storage, key, value){
		window[storage].setItem(key, value);
	};
})(this); 

//TODO register require js
//----------------------------------- 
(function() {
	'use strict';
	
	require.config({
		appDir: "/miwawa/",
		baseUrl: "resources/lib",
		paths: {
			"moment": "miwawa/1.0.2/js/plugins/moment/2.11.1/js/moment-with-locales.min",
			"avatar": "miwawa/1.0.2/js/plugins/avatar/fullAvatarEditor",
			"sockjs": "miwawa/1.0.2/js/plugins/sockjs/sockjs.min",
			"swfobject": "miwawa/1.0.2/js/plugins/avatar/swfobject",
			"sweetalert": "miwawa/1.0.2/js/plugins/sweetalert/1.1.3/js/sweetalert.min",
			"handlebars": "miwawa/1.0.2/js/plugins/handlerbars/4.0.5/js/handlebars-v4.0.5",
			
			"jquery": "miwawa/1.0.2/js/jquery/jquery-1.11.3.min",
			"jquery.bootstrap": "bootstrap/3.3.5/js/bootstrap.min",
			"jquery.bootstrap.tree": "miwawa/1.0.2/js/core/module/bootstrap/tree",
			"jquery.bootstrap.table": "miwawa/1.0.2/js/core/module/bootstrap/table",
			"jquery.bootstrap.notify": "miwawa/1.0.2/js/core/module/bootstrap/notify",
			"jquery.bootstrap.tabdrop": "miwawa/1.0.2/js/core/module/bootstrap/tabdrop",
			"jquery.bootstrap.editable": "miwawa/1.0.2/js/core/module/bootstrap/editable",
			"jquery.bootstrap.validator": "miwawa/1.0.2/js/core/module/bootstrap/validator",
			"jquery.bootstrap.bootbox": "bootstrap/extends/bootstrap-bootbox/4.4.0/js/bootbox.min",
			
			"jquery.plugin.resize": "miwawa/1.0.2/js/jquery/jquery-resize-1.1.0",
			"jquery.plugin.calendar": "miwawa/1.0.2/js/core/module/plugins/calendar",
			"jquery.plugin.amaranjs": "miwawa/1.0.2/js/jquery/amaranjs/0.5.4/js/jquery.amaran.min",
			"jquery.plugin.slimscroll": "miwawa/1.0.2/js/jquery/slimscroll/1.3.3/js/jquery.slimscroll.min",
			"jquery.plugin.nicescroll": "miwawa/1.0.2/js/jquery/nicescroll/3.6.6/js/jquery.nicescroll.min",
			
			"jquery.plugin.form": "miwawa/1.0.2/js/core/module/formplugin/form"
		},
		shim: {
			"avatar": {deps : ["swfobject"], exports : "fullAvatarEditor"},
			"swfobject": {exports: "swfobject"},
			"sweetalert": {deps : ["css!miwawa/1.0.2/js/plugins/sweetalert/1.1.3/css/sweetalert.css"]},
			"jquery.bootstrap": {deps: ["jquery"]},
			"jquery.plugin.amaranjs": {
				deps: ["jquery","css!miwawa/1.0.2/js/jquery/amaranjs/0.5.4/css/amaran.min.css"], 
				exports : "jQuery.amaran"
			},
			"jquery.plugin.slimscroll": {deps: ["jquery"], exports : "jQuery.fn.slimScroll"}
		},
		map:{
			"*":{
				"css": "miwawa/1.0.2/js/core/requirejs/plugins/css",
				"text": "miwawa/1.0.2/js/core/requirejs/plugins/text",
				"domReady": "miwawa/1.0.2/js/core/requirejs/plugins/domReady"
			}
		},
		wrapShim: true,
		waitSeconds: 0
	});
	
	define(['jquery'],function(jQuery){
		
		require(['moment','jquery.bootstrap.notify'],function(moment, notify){
			
			var $options = {
				ajaxOptions: {
					url: "",
					type: 'POST',
					data: undefined,
					async: true,
					cache: false,
					dataType: "json",
					beforeSend: function(xhr){},
					success: function(data, status, xhr){},
					error: function(xhr, status, error){}
				},
				searchOptions: {
					searchAction: "/miwawa/{dbname}/common/search.json",
					searchEntity: "",
					searchQuerys: undefined,
					searchOrders: undefined,
					searchPaging: { "offset": 0, "limit": 0 },
					searchSuccess: undefined
				}
			};
			
			var calculateObjectValue = function (self, name, args, defaultValue) {
		        var func = name;

		        if (typeof name === 'string') {
		            // support obj.func1.func2
		            var names = name.split('.');

		            if (names.length > 1) {
		                func = window;
		                jQuery.each(names, function (i, f) {
		                    func = func[f];
		                });
		            } else {
		                func = window[name];
		            }
		        }
		        if (typeof func === 'object') {
		            return func;
		        }
		        if (typeof func === 'function') {
		            return func.apply(self, args);
		        }
		        return defaultValue;
		    };
			
			jQuery.extend({
				ajaxsend:function(options){
					return jQuery.ajax(jQuery.extend({}, $options.ajaxOptions, options));
				},
				message:{
					notify:function(msg, place){
						require(['jquery.plugin.amaranjs'],function(amaranjs){
							jQuery.amaran({
								'content'	 : msg,
								'theme'		 : 'awesome ok',
						        'sticky'     : true,
						        'position'   : place || 'top right',
						        'closeButton': true
							});
						});
					},
					warning:function(msg, place){
						notify.warning("", msg, place);
					},
					success:function(msg, place){
						notify.success("", msg, place);
					},
					confirm:function(msg, callback){
						require(['jquery.bootstrap.bootbox'],function(bootbox){
							bootbox.setDefaults("locale","zh_CN"); 
							bootbox.confirm({
								message: msg,
								callback: callback
							});
						});
					},
					alert:function(msg, callback){
						require(['jquery.bootstrap.bootbox'],function(bootbox){
							bootbox.setDefaults("locale","zh_CN"); 
							bootbox.alert({
								message: msg,
								callback: callback
							});
						});
					}
				},
				utils:{
					week:{"周一":1,"周二":2,"周三":3,"周四":4,"周五":5,"周六":6,"周日":7},
					weeks:["周日","周一","周二","周三","周四","周五","周六","周日"],
					daysOfWeekDiff:{
						"周一":{"周一":0,"周日":1,"周六":2,"周五":3,"周四":4,"周三":5,"周二":6},
						"周二":{"周二":0,"周一":1,"周日":2,"周六":3,"周五":4,"周四":5,"周三":6},
						"周三":{"周三":0,"周二":1,"周一":2,"周日":3,"周六":4,"周五":5,"周四":6},
						"周四":{"周四":0,"周三":1,"周二":2,"周一":3,"周日":4,"周六":5,"周五":6},
						"周五":{"周五":0,"周四":1,"周三":2,"周二":3,"周一":4,"周日":5,"周六":6},
						"周六":{"周六":0,"周五":1,"周四":2,"周三":3,"周二":4,"周一":5,"周日":6},
						"周日":{"周日":0,"周六":1,"周五":2,"周四":3,"周三":4,"周二":5,"周一":6},
					},
					daysOfWeekDisabled:{
						"周日":[1,2,3,4,5,6],
						"周一":[0,2,3,4,5,6],
						"周二":[0,1,3,4,5,6],
						"周三":[0,1,2,4,5,6],
						"周四":[0,1,2,3,5,6],
						"周五":[0,1,2,3,4,6],
						"周六":[0,1,2,3,4,5]
					},
					getDaysOfDiff:function(week){
						var curdate = moment();
						var curweek = jQuery.utils.weeks[curdate.isoWeekday()];
						var diff = jQuery.utils.daysOfWeekDiff[curweek][week];
						return curdate.subtract(diff, 'days');
					},
					toArray:function(orig,regex){
						return regex ? orig.split(regex) : orig.split(",");
					},
					toTotal:function(array){
						var total=0;
						for(var i in array){
							total+=new Number(array[i]);
						}
						return total;
					},
					toSQLEscapeValue:function(array){
						return array ? array.join("','") : null;
					},
					nowtimer:function(){
						jQuery('[data-now]').each(function(){
							var element = jQuery(this),
					          	format = element.data('format');

							function updateTime() {
						        var dt = moment(new Date()).format(format);
						        element.text(dt);
							}
							updateTime();
							setInterval(updateTime, 1000);
						});
					},
					loading:function(message, shown, zindex){
						if(zindex) jQuery(".loading-waiter").css("z-index",zindex);
						if(message) jQuery(".loading-waiter .loader .texting").text(message);
						jQuery(".loading-waiter")[shown]();
					}
				}
			});
			
			jQuery.fn.extend({
				template:function(method, options){
					if(method && typeof(method)=="string") return this.template.methods[method](this, options);
				},
				ajaxSearch:function(options){
					options = jQuery.extend({}, $options.searchOptions, this.data(), typeof options === "object" && options);
					
					if(options.searchQuerys && options.searchQuerys.and){
						jQuery.each(options.searchQuerys.and,function(i, o){
							if(o.fieldValues){
								jQuery.extend(o, {"fieldValues":calculateObjectValue(null, o.fieldValues, null, o.fieldValues)});
							}
						});
					}
					
					if(options.searchQuerys && options.searchQuerys.or){
						jQuery.each(options.searchQuerys.or,function(i, o){
							if(o.fieldValues){
								jQuery.extend(o, {"fieldValues":calculateObjectValue(null, o.fieldValues, null, o.fieldValues)});
							}
						});
					}
					
					var querymap = jQuery.extend({},options.searchEntity,options.searchPaging,options.searchOrders,options.searchQuerys);
					
					jQuery.ajax(jQuery.extend({}, $options.ajaxOptions, {
						url: options.searchAction.replace("{dbname}",dbname),
						data: querymap,
						success: options.searchSuccess
					}));
				},
				searched:function(params, options){
					if(typeof(params) == "string") params = jQuery.parseJSON(params);
					
					var querydata = this.querydata(options.querys, params);
					
					var defaults = {
						url : this.attr("action").replace("{dbname}", dbname),
						type : 'POST',
						data : {
							"entityClass":this.attr("name"),
							"search":params.search,
							"offset":params.offset,
							"limit":params.limit,
							"order":querydata.order,
							"and":querydata.and,
							"or":querydata.or
						},
						async: true,
						cache: false,
						dataType: "json",
						beforeSend: function(xhr){},
						success: function(data, status, xhr){},
						error: function(xhr, status, error){}
					};
					
					if(options) jQuery.extend(defaults, options);
					
					jQuery.ajax(defaults);
				},
				querydata:function(querys, params){
					var querymap = jQuery.extend(true, {}, {"order":[], "and":[], "or":[]}, querys);
					
					jQuery("[data-search-group]", this).each(function(i, n){
						var $this = jQuery(this);
						var _opts = $this.data();

						if(!_opts.ignore){
							querymap[_opts.searchGroup].push({
								"operator": _opts.searchOperation,
								"fieldType": _opts.searchType,
								"fieldName": $this.attr("name"),
								"fieldValue": $this.val() ? $this.val() : null,
								"fieldValues": _opts.searchValues ? window[_opts.searchValues] : null
							});
						}
					});
					
					// 字段排序
					jQuery("[data-search-sort]", this).each(function(i, n){
						var $this = jQuery(this);
						var _opts = $this.data();
						var _order = jQuery.extend({"sort":_opts.searchSort, "order":_opts.searchOrder}, params.sort ? params : {});
						
						querymap["order"].push(_order);
					});
					
					return querymap;
				}
			});
			
			jQuery.fn.template.methods = {
				loader:function(elem, options){
					var _opts = jQuery.extend({
						mode: "create",
						data: null,
						tempid: null,
						tempurl: "template.html",
						params: null,
						helpers: null,
						onLoaded: null
					}, options);
					
					var url = _opts.tempurl+"?"+Date.parse(new Date());
					if(_opts.params){ url += _opts.params }
					
					require(['text!'+url, 'handlebars'],function(html, Handlebars){
						var content = _opts.tempid ? jQuery("<div>").html(html).find(_opts.tempid).html() : html;

						(_opts.mode == "create" ? elem.empty() : elem).append(function(){
							var compile = Handlebars.compile(content);

							if(_opts.helpers && typeof(_opts.helpers) == "object"){
								jQuery.each(_opts.helpers, function(key, fun){
									Handlebars.registerHelper(key, fun);
								});
							}
							
							Handlebars.registerHelper("checked", function(value, text){
								if(value == text){
									return "checked";
								}
							});
							
							return _opts.data ? compile(_opts.data) : content;
						});
						
						if(_opts.onLoaded){
							require(['domReady'],function(domReady){
								domReady(function(){ 
									typeof _opts.onLoaded == "string" ? window[_opts.onLoaded](_opts.data) : _opts.onLoaded(_opts.data); 
								});
							});
						}
					});
					
					return elem;
				}
			}
		});
		
	});
})(this);

(function(window, document, $, undefined){
	'use strict';
	
	// 列表查询
	window["handlerSearch"] = function(params){
		jQuery(this.options.formSearch).searched(params.data, {
			querys:this.options.searchQuerys,
			success:function(data){
				params.success(data);
				params.complete();
			}
		});
	};
	
	// TODO 列表加载完后调用
	window["handlerSuccess"] = function(status){
		jQuery(".loading-container").hide();
	};
})(window, document, window.jQuery);
